//
//  ChatDetailViewCtrl.m
//  DogeLegs
//
//  Created by 宋华 on 2017/8/26.
//  Copyright © 2017年 宋华. All rights reserved.
//

#import "ChatDetailViewCtrl.h"
#import "ChatTableView.h"
#import "LXChatBox.h"
#import "SendImageView.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "ChatProtocol.h"
#import "ChatManager.h"
#import "MessageManager.h"
#import "KTPhotoScrollViewController.h"

@interface ChatDetailViewCtrl () <LXChatBoxDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,ChatDelegate> {
    NSString *suffixFile;
}

@property (nonatomic,assign) __block NSInteger duringTime;

@property (nonatomic,strong) ChatProtocol *chatProtocol;

@property (nonatomic,strong) ChatTableView *atableView;

@property (nonatomic,strong) LXChatBox *chatBox;

@property (nonatomic,strong) UIImagePickerController *imagePickerController;

@property (nonatomic,strong) UIImageView *volumeImageView;

@property (nonatomic,strong) SendImageView *imageView;

@property (nonatomic,strong)NSMutableArray *msglists;

@end

@implementation ChatDetailViewCtrl


- (void)dealloc{
    [NSNotificationCenter removeAllNotification:self];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.duringTime =0;  //设时初使时间
    
    self.title = [self returnNickName];
    
    [self.chatBox setIsDisappear:NO];
    
    [self.view addSubview:self.atableView];
    
    [self reloadTabByCache];
 
    [NSNotificationCenter addMessageListMsgNF:self action:@selector(handleMessageListMsg:)];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [self.chatProtocol uploadMessageStatus:self.rcChat.friendid];
    [[VoiceChatModule getInstance] stopPlayAudio];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 界面
- (void)reloadTabByCache {
   self.msglists = [self.chatProtocol queryChatList:self.rcChat.friendid curCount:self.msglists.count];
    self.atableView.results = self.msglists;
    [self.atableView reloadData];
    [self scrollToBottomAnimated:YES];
}

- (void)loadImageView:(UIImage *)image withFileCode:(NSString *)fileCode {
    SendImageView *imageView = [[SendImageView alloc]initWithFrame:self.view.frame WithImage:image];
    [self.view addSubview:imageView];
    
    imageView.sendImageBlick = ^{
        
        suffixFile = [[fileCode pathExtension] lowercaseString];
        [self uploadImage:image];
    };
}

//延迟操作
- (void)performClick {
    self.volumeImageView.hidden = YES;
}


//图片浏览
- (void)imageClickWithCurrentChatMessage:(ChatMessage *)curentModel {
    
    if (curentModel.mediaStatus == MEDIA_DOWNLOAD_SUCC || curentModel.msgSourceType == CHAT_MSG_SEND) {
        //要判断图片的长和宽
        NSString* imageUrl=LocalImagePath(curentModel.toFriendid,curentModel.contentPath);
        NSMutableArray *imageArr = [NSMutableArray array];
        [imageArr addObject:imageUrl];
        KTPhotoScrollViewController *newController = [[KTPhotoScrollViewController alloc]
                                                      initWithDataSource:imageArr
                                                      andStartWithPhotoAtIndex:0];
        [self.navigationController pushViewController:newController animated:NO];
    }
}

#pragma mark -
#pragma mark - ChatDelegate
- (NSString *)returnNickName {
    if(self.rcChat.friendName.length > 0) {
        return self.rcChat.friendName;
    }
    return @"哈哈";
}

//录音时长
- (NSInteger)getDuringTime {
    return self.duringTime;
}

#pragma mark--- 代理---
#pragma mark - LXChatBoxDelegate
- (void)changeStatusChat:(CGFloat)chatBoxY{
    NSLog(@"chatBoxY is %f",chatBoxY);
    self.atableView.frame = CGRectMake(0, 0, kScreenWidth, chatBoxY);
    [self.atableView downBottom:YES];
}

- (void)chatBoxSendChatBoxItem:(LXChatBoxItem)item {
    
    switch (item) {
        case LXChatBoxItemAlbum:
            [self selectImage:UIImagePickerControllerSourceTypePhotoLibrary];
            break;
        case LXChatBoxItemCamera:
            [self selectImage:UIImagePickerControllerSourceTypeCamera];
            break;
            
        case LXChatBoxItemVideo:
            break;
        case LXChatBoxItemDoc:
            break;
        default:
            break;
    }
}

- (void)selectImage:(UIImagePickerControllerSourceType)type {
    self.imagePickerController.sourceType = type;
    [self presentViewController:self.imagePickerController animated:YES completion:nil];
}

#pragma mark UIImagePickerControllerDelegate
//适用获取所有媒体资源，只需判断资源类型
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]){
        
        NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
        ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
        {
            ALAssetRepresentation *representation = [myasset defaultRepresentation];
            suffixFile = [[[representation filename] pathExtension] lowercaseString];
        #warning 需要修改
            //上传图片
            [self uploadImage:info[UIImagePickerControllerEditedImage]];
        };
        
        ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
        [assetslibrary assetForURL:imageURL
                       resultBlock:resultblock
         
                      failureBlock:nil];
    }else{
        //如果是视频
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark  -发送图片和语音消息
- (void)uploadImage:(UIImage *)image {
    NSData *data = UIImagePNGRepresentation(image);
    ChatMessage *ms = [self insertImageTable:image];
    [MessageManager sendChatMessage:self.rcChat.friendid chatMessage:ms isReSend:NO];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        UIImage *maxImage = scaleImageToMaxSize(image);
//        [self.chatProtocol uploadStreamarameter:@{} withStreamType:maxImage];
    });
}

- (ChatMessage *)insertImageTable:(UIImage *)aImage
{
    if (aImage==nil) {
        return nil;
    }
    //保存图片
    NSString* realSavePath = [FilePathMode creatImageFile:self.rcChat.friendid];
    UIImage *maxImage = scaleImageToMaxSize(aImage);
    NSData *data = UIImageJPEGRepresentation(maxImage, 1.0);
    [data writeToFile:realSavePath atomically:YES];
    
    //写缩略图
    NSString *realThumbPath = [ImageAddition thumbPath:realSavePath];
    
    NSData *thumbData = [ImageAddition thumbImage:nil origin:aImage compressionQuality:0.1f size:300];
    
    if (thumbData) {
        //缩略图结果不管
        [thumbData writeToFile:realThumbPath atomically:YES];
    }
    ChatMessage *msg=[[ChatManager sharedInstance] saveChatMessage:ChatMsgBodyType_Image msgContent:nil contentPath:[realSavePath lastPathComponent] voiceLength:nil recentChat:self.rcChat];
    
    [self.msglists addObject:msg];
    self.atableView.results = self.msglists;
    [self.atableView reloadData];
    
    [self scrollToBottomAnimated:YES];
    return msg;

}

- (void)uploadVoice:(NSString *)voicePath {
    NSString *relativePath = [voicePath lastPathComponent];
    ChatMessage *msg=[[ChatManager sharedInstance] saveChatMessage:ChatMsgBodyType_Voice msgContent:nil contentPath:relativePath voiceLength: intToString(self.duringTime) recentChat:self.rcChat];
    [self.msglists addObject:msg];
    self.atableView.results = self.msglists;
    [self.atableView reloadData];
    [self scrollToBottomAnimated:YES];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //需要上传
        [self.chatProtocol uploadStreamarameter:@{} withStreamType:voicePath];
        
        

    });
}


#pragma mark - delegate - LXChatBoxDelegate 发送文字消息
//发送消息
-(void)chatBoxSendTextMessage:(NSString *)message{
    if ([message length]==0) {
        return;
    }
#warning 发送消息
    ChatMessage *msg  = [[ChatManager sharedInstance] saveChatMessage:ChatMsgBodyType_Text msgContent:message contentPath:nil voiceLength:nil recentChat:self.rcChat];
    @synchronized(self.atableView)
    {
        [self.msglists addObject:msg];
        self.atableView.results = self.msglists;
        [self.atableView reloadData];
        [self scrollToBottomAnimated:YES];
    }
    
    NSDictionary *dict = @{@"message":message,@"recive":objectToString(self.rcChat.friendid),@"sender":objectToString(USERID)};
    [self.chatProtocol senderText:dict];
}


#pragma mark - UIScrollView
- (void)scrollToBottomAnimated:(BOOL)animated
{
    NSInteger rows = [self.atableView numberOfRowsInSection:0];
    if(rows > 0) {
        [self.atableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows-1 inSection:0]
                              atScrollPosition:UITableViewScrollPositionBottom
                                      animated:animated];
    }
}



#pragma mark - 通知
- (void)handleMessageListMsg:(NSNotification *)not {
    NSLog(@"接收消息要处理");
    //添加
//    [self.msglists addObject:<#(nonnull id)#>]
}

#pragma mark - getter 
- (UIImagePickerController *)imagePickerController {
    
    if(!_imagePickerController) {
        
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
    }
    
    return _imagePickerController;
}


- (UIImageView *)volumeImageView {
    
    if(!_volumeImageView) {
        _volumeImageView = [[UIImageView alloc]initWithFrame:CGRectMake(kScreenWidth/2-80, kScreenHeight/2-80, 160, 160)];
        _volumeImageView.hidden = YES;
        
        [self.view addSubview:_volumeImageView];
    }
    return _volumeImageView;
}


- (ChatProtocol *)chatProtocol {
    
    if(!_chatProtocol) {
        
        _chatProtocol = [[ChatProtocol alloc]init];
        _chatProtocol.chatDelegate = self;
        _chatProtocol.rcChat = self.rcChat;
        WeakSelf(ws);
        _chatProtocol.chatSourceBlock = ^(NSMutableArray *results) {
            
            
        };
    }
    return _chatProtocol;
}

- (ChatTableView *)atableView {
    
    if(!_atableView){
        
        _atableView = [[ChatTableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-64-50) style:UITableViewStylePlain];
        _atableView.chatProtocol = self.chatProtocol;
        //        _atableView.backgroundColor = [UIColor redColor];
        WeakSelf(ws);
        _atableView.scrollWillBeginDragging = ^{
            
            [ws.chatBox scrollResignFirstResponeer];
        };
        
        _atableView.imageClickBlock = ^(ChatMessage *currentModel) {
            
            [ws imageClickWithCurrentChatMessage:currentModel];
        };
    }
    return _atableView;
}


- (LXChatBox *)chatBox {
    
    if(!_chatBox) {
        
        _chatBox =[[LXChatBox alloc]initWithFrame:CGRectMake(0, kScreenHeight-50 - kNavAndStatusBarHeight, kScreenWidth, 50) WithchatBoxType:ChatTypePlan];
        _chatBox.maxVisibleLine = 3;
        _chatBox.delegate = self;
        _chatBox.rcChat = self.rcChat;
        _chatBox.parentViewHeight = kScreenHeight - kNavAndStatusBarHeight;
        WeakSelf(ws);
        _chatBox.downVoice=^{
            
            ws.volumeImageView.image = [UIImage imageNamed:@"voice_1"];
        };
        _chatBox.AudioRecorderBlock = ^(NSURL *recordUrl,NSInteger timer) {
            //语音发送回调
            
            ws.duringTime = timer;
            [ws uploadVoice:recordUrl.absoluteString];
            ws.volumeImageView.hidden = YES;
        };
        //音量回调
        _chatBox.VolumeBlock = ^(CGFloat volume) {
            //音量大小
            int index =(int)(volume *100)%6+1;
            ws.volumeImageView.hidden = NO;
            [ws.volumeImageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"voice_%d",index]]];
        };
        //录音时间短
        _chatBox.voiceFail = ^{
            
            [ws.volumeImageView setImage:[UIImage imageNamed:@"voiceShort"]];
            [ws performSelector:@selector(performClick) withObject:nil afterDelay:1];
            
        };
        //移走录音回调
        _chatBox.moveVoice=^{
            
            [ws.volumeImageView setImage:[UIImage imageNamed:@"cancelVoice"]];
        };
        //取消录音回调
        _chatBox.cancelVoice=^{
            ws.volumeImageView.hidden = YES;
        };
        
        _chatBox.voiceOverflowBlock = ^{
            [SVProgressHUD showErrorWithStatus:@"Voice is to long,Please try again"];
            ws.volumeImageView.hidden = YES;
        };
        
        _chatBox.overflowBlock = ^{
            [SVProgressHUD showErrorWithStatus:@"Text is to long,Please try again"];
        };
        
        _chatBox.textView.pasteBlock = ^(UIImage *image,NSString *fileCode) {
            
            [ws.view endEditing:YES];
            
            [ws loadImageView:image withFileCode:fileCode];
        };
        
        [self.view addSubview:_chatBox];
    }
    
    return _chatBox;
}

- (NSMutableArray *)msglists {
    if (_msglists == nil) {
        _msglists = [NSMutableArray array];
    }
    return _msglists;
}

@end
